package cn.fintecher.gis.filter;

import cn.fintecher.gis.model.session.SessionModel;
import cn.fintecher.gis.service.OperatorService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by ChenChang on 2018/9/3.
 */
@Component
@WebFilter(urlPatterns = {"/api/*"}, filterName = "operatorTokenFilter")
public class OperatorTokenFilter extends OncePerRequestFilter {

    private static Logger log = LoggerFactory.getLogger(OperatorTokenFilter.class);
    @Autowired
    private OperatorService operatorService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (StringUtils.contains(request.getRequestURL().toString(), "message-webSocket")) {
            filterChain.doFilter(request, response);
            return;
        }
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            filterChain.doFilter(request, response);
            return;
        }

        log.debug(String.format("%s request to %s", request.getMethod(), request.getRemoteAddr()+request.getRequestURL().toString()));
        if (StringUtils.contains(request.getRequestURL().toString(), "/operator/login")
                || StringUtils.contains(request.getRequestURL().toString(), "api/dataDictController/getAll")
                || StringUtils.contains(request.getRequestURL().toString(), "api/dataDictController/DataDictHashCode")
                || StringUtils.contains(request.getRequestURL().toString(), "api/uploadFile/upload")
                || StringUtils.contains(request.getRequestURL().toString(), "swagger")
                || StringUtils.contains(request.getRequestURL().toString(), "api-docs")) {
            filterChain.doFilter(request, response);
            return;
        }
        String accessToken = request.getHeader("X-OperatorToken");

        if (StringUtils.isBlank(accessToken)) {
            log.debug("access token is empty");
            response.setStatus(403);
            return;
        }
        SessionModel operator = operatorService.findOperatorByToken(accessToken);
        if (Objects.isNull(operator)) {
            log.debug("access token is wrong");
            response.setStatus(403);
            return;
        }
        log.debug("access token ok");
        filterChain.doFilter(request, response);

    }
}
